const utils = require('../../utils/utils.js');
const { adapterHeight } = utils.getAdapterheight();

const { globalData } = getApp();
// const { Service: { Status, Message, File } } = globalData;

const RongEmoji = require('../lib/RongIMEmoji-2.2.6.js');
RongEmoji.init();

const softKeyboardHeight = 210;

const getToView = (context) => {
  let { messageList } = context.data;
  let index = messageList.length - 1;
  let message = messageList[index] || {};
  return message.uId || '';
};

const setKeyboardPos = (context, keyboardHeight, adapterHeight) => {
  keyboardHeight = keyboardHeight || 0;
  let data;
  let isScroll = (keyboardHeight > 0);
  console.log(keyboardHeight);
  if (isScroll){
    data = {
      bottom: adapterHeight + keyboardHeight,
      isShowEmojiSent: false,
      toView: getToView(context)
    };
  }else{
    data = {
      bottom: adapterHeight + keyboardHeight,
      isShowEmojiSent: false
    };
  }
  context.setData(data);
};

const showSoftKeyboard = (context, display) => {
  context.setData({
    display: display,
    bottom: softKeyboardHeight,
    isShowKeyboard: false,
    toView: getToView(context)
  });
};
const hideSoftKeyboard = (context) => {
  context.setData({
    display: {
      emoji: 'none',
      more: 'none'
    }
  });
};

const hideKeyboard = (context) => {
  let keyboardHeight = 0;
  let { adapterHeight } = context.data;
  setKeyboardPos(context, keyboardHeight, adapterHeight);
  hideSoftKeyboard(context);
};

const formatEmojis = () => {
  let list = RongEmoji.list;
  return utils.sliceArray(list, {size: 24});
};

const getMessageList = (context, params) => {
  let {position} = params;
  // return Message.getList(params).then((result) => {
    let messages = context.data.messageList;
  //   let hasMore = result.hasMore;

    let { messageList, playingVoice, playingMusicComponent} = context.data;
    // messageList = messages.concat(messageList);
    let toView = '';
    if(params.position == 0){
      let index = messageList.length - 1;
      let message = messageList[index] || {};
      toView = message.uId || '';
    }
    let isFirst = (position == 0);
  //   if (!hasMore && !isFirst){
  //     // 灰条提示
  //     toView = 'message-notify-without';
  //     context.setData({
  //       hasMore: hasMore
  //     });
  //   }

    if(isFirst){
      context.setData({
        messageList: messageList,
        isAllowScroll: true,
        toView: toView
      });
    }else{
      context.setData({
        messageList: messageList,
        isAllowScroll: true
      });
    } 
  // });
};

const updatePlayStatus = (context, { newMusicComponent, isPlaying}, callback) => {
  let { data: { messageList, playingMusicComponent} } = context;
  callback = callback || utils.noop;
  messageList.map((message) => {
    callback(message);
    return message;
  });
  if (playingMusicComponent) {
    playingMusicComponent.setData({
      isPlaying
    });
  }
  if (newMusicComponent){
    context.setData({
      playingMusicComponent: newMusicComponent,
      messageList
    });
  }else{
    context.setData({
      messageList
    });
  }
  
};

const stopPlayMusic = (context) => {
  let newMusicComponent = null, isPlaying = false;
  updatePlayStatus(context, { newMusicComponent, isPlaying }, (message) => {
    utils.extend(message, { isPlaying });
  });
};

const getImageUrls = (context) => {
  let {messageList} = context.data;
  return messageList.filter(message => {
    return message.name == 'ImageMessage';
  }).map(message => {
    return message.content.imageUri;
  });
};

const onLoad = (context, query) => {
  let { title, type, targetId } = query;
  wx.setNavigationBarTitle({
    title: '客服',
  })
  context.setData({
    adapterHeight: adapterHeight,
    type,
    targetId
  });
  let keyboardHeight = 0;
  setKeyboardPos(context, keyboardHeight, adapterHeight);

  let position = 0;
  let count = 15;
  // getMessageList(context, { type, targetId, position, count });
};

const onUnload = (context) => {
  let { playingVoice, playingMusicComponent } = context.data;
  if (playingVoice) {
    playingMusicComponent.stop();
  }
  if (playingMusicComponent) {
    playingMusicComponent.stop();
  }
};

const showVoice = (context) => {
  let { adapterHeight } = context.data;
  context.setData({
    isShowKeyboard: false
  });
  hideKeyboard(context);
};

const showKeyboard = (context) => {
  context.setData({
    isShowKeyboard: true
  });
  hideKeyboard(context);
};

const recorderManager = wx.getRecorderManager()

const startRecording = (context) => {
  context.setData({
    isRecording: true
  });
  let record = () => {
    recorderManager.start({
      format: 'mp3'
    });
  };
  wx.getSetting({
    success(res) {
      if (!res.authSetting['scope.record']) {
        wx.authorize({
          scope: 'scope.record',
          success: record
        })
      } else {
        record();
      }
    }
  })
};

const stopRecording = (context) => {
  context.setData({
    isRecording: false
  });
  recorderManager.onStop((res) => {
    console.log('recorder stop', res)
    const { tempFilePath, duration } = res
    File.upload({
      path: tempFilePath
    }).then(file => {
      console.log(file)
      let content = {
        content: file.downloadUrl,
        duration: Math.ceil(duration / 1000)
      };
      let { type, targetId, messageList } = context.data;
      // Message.sendVoice({
      //   type,
      //   targetId,
      //   content
      // }).then(message => {
      //   messageList.push(message);
      //   context.setData({
      //     messageList,
      //     toView: message.uId
      //   });
      // });
    });
  })
  recorderManager.stop();
};

const showEmojis = (context) => {
  showSoftKeyboard(context, {
    emoji: 'block',
    more: 'none'
  });
};

const showMore = (context) => {
  showSoftKeyboard(context, {
    emoji: 'none',
    more: 'block'
  });
};

const selectEmoji = (context, event) => {
  var content = context.data.content;
  var { emoji } = event.target.dataset;
  content = content + emoji;
  context.setData({
    content: content,
    isShowEmojiSent: true
  });
};

const sendText = (context) => {
  let { content, type, targetId, messageList } = context.data;
  context.setData({
    content: '',
    isShowEmojiSent: false
  });
  if (content.length == 0) {
    return;
  }
  sendMessage(context,content,"message");
  // Message.sendText({
  //   type,
  //   targetId,
  //   content
  // }).then(message => {
  //   messageList.push(message);
  //   context.setData({
  //     messageList,
  //     toView: message.uId
  //   });
  // });
};

const getMoreMessages = (context) => {
  // let { type, targetId, hasMore } = context.data;
  // let position = null;
  // let count = 5;
  // if (hasMore) {
  //   context.setData({
  //     isAllowScroll: false
  //   });
  //   getMessageList(context, { type, targetId, position, count });
  // }
};

const sendImage =  (context) => {
  
  wx.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      let { tempFilePaths } = res;
      let tempFilePath = tempFilePaths[0];
      wx.getImageInfo({
        src: tempFilePath,
        success: (res) => {
          var lists = [];
          var messageList = lists.concat(context.data.messageList);
          var list = {
            uId: new Date().getTime(),
            name: 'ImageMessage',
            direction: 'sender',
            fromUser: globalData.userInfo.nickName,
            toUser: "kefu",
            sender: {
              avatar:globalData.userInfo.avatarUrl,
            },
            content: {
              imageUri: tempFilePath
            }
          }
          messageList.push(list);
          context.setData({
            messageList,
            toView: list.uId
          });

          wx.uploadFile({
            url: 'https://wx.my56app.com/appim/savePicture',
            filePath: tempFilePath,
            name: 'file',
            success(res) {
              console.log('==========='+res.data)
              const data = res.data
              var path = 'http://www.my56.com:8080/app/' + data
              sendMessage(context, path, 'picture')
            },fail(res) {
              console.log('===========' + res)
            }
          });
        }
      })
    }
  })
};

const sendMusic = (context) => {
  // let { content, type, targetId, messageList } = context.data;
  // Message.sendMusic({
  //   type,
  //   targetId
  // }).then(message => {
  //   messageList.push(message);
  //   context.setData({
  //     messageList,
  //     toView: message.uId
  //   });
  // });
};

const playVoice = (context, event) => {
  // let voiceComponent = event.detail;
  // let { playingVoice } = context.data;
  // if (playingVoice) {
  //   let playingId = playingVoice.__wxExparserNodeId__;
  //   let voiceId = voiceComponent.__wxExparserNodeId__;
  //   // 两次播放为同个音频，状态保持不变
  //   if (playingId == voiceId) {
  //     return;
  //   }
  //   let { innerAudioContext } = playingVoice.data;
  //   playingVoice.setData({
  //     isPlaying: false
  //   });
  //   innerAudioContext.stop();
  // }
  // context.setData({
  //   playingVoice: voiceComponent
  // });
};

const playMusic = (context, event) => {
  let newMusicComponent = event.detail;
  let { playingMusicComponent, messageList } = context.data;
  let { properties: { message: { messageUId: newPlayId } } } = newMusicComponent
  let playingId = '';

  // 连续点击播放不同音乐
  if (playingMusicComponent) {
    let { properties: { message } } = playingMusicComponent;
    playingId = message.messageUId;
    //先停止上一个，再播放
    let isDiffMusic = (playingId != newPlayId);
    if (isDiffMusic) {
      let { innerAudioContext } = playingMusicComponent.data;
      playingMusicComponent.setData({
        isPlaying: false
      });
      innerAudioContext.stop();
    }
  }
  let isPlaying = false;
  updatePlayStatus(context, { newMusicComponent, isPlaying }, (message) => {
    let { messageUId } = message;
    // 默认为未播放状态
    isPlaying = false;
    if (messageUId == newPlayId) {
      isPlaying = true;
    }
    utils.extend(message, { isPlaying });
  });
};

const previewImage = (context, event) => {
  let currentImageUrl = event.detail;
  let urls = getImageUrls(context);
  if (utils.isEmpty(urls)) {
    urls.push(currentImageUrl);
  }
  wx.previewImage({
    current: currentImageUrl,
    urls: urls
  })
};

const stopMusic = (context, event) => {
  let musicComponent = event.detail;
  let { properties: { message: { messageUId } } } = musicComponent;

  let { messageList, playingMusicComponent } = context.data;
  if (playingMusicComponent) {
    let { data: { innerAudioContext } } = playingMusicComponent;
    innerAudioContext.stop();
  }
  musicComponent.setData({
    isPlaying: false
  });
  stopPlayMusic(context);
};

const sendMessage = (context,content, type) => {
  var message = {
    fromUser: globalData.userInfo.nickName,
    toUser: 'kefu',
    content: content,
    timestamp: new Date().getTime(),
    type: type
  };
  var messageStr = JSON.stringify(message)
  wx.sendSocketMessage({
    data: messageStr,
  })
  if (type != 'message') return;
  if (type == 'picture') return;
  pushMessage(context,message);
}

const pushMessage = (context, message) => {
  var lists = [];
  var messageList = lists.concat(context.data.messageList);
  var list = {
    uId: new Date().getTime(),
    name: 'TextMessage',
    direction: message.fromUser == 'kefu' ? 'receiver' : 'sender',
    fromUser: message.fromUser,
    toUser: message.toUser,
    sender: {
      avatar: message.fromUser == 'kefu' ? '../images/emoji.png' : globalData.userInfo.avatarUrl,
    },
    content: {
      content: message.content
    }
  }
  messageList.push(list);
  context.setData({
    messageList,
    toView: list.uId
  });
}

Page({
  data: {
    content: '',
    messageList: [],
    bottom: 0,
    adapterHeight: 0,
    display: {
      emoji: 'none',
      more: 'none'
    },
    emojis: formatEmojis(),
    isShowEmojiSent: false,
    isRecording: false,
    isShowKeyboard: false,
    hasMore: true,
    toView: '',
    playingVoice: null,
    playingMusicComponent: null,
    isAllowScroll: true,
    scrollTop: 0,
    questionMessage: '',
    isFirstLoad:true
  },
  hideKeyboard: function () {
    hideKeyboard(this);
  },
  selectEmoji: function (event) {
    selectEmoji(this, event);
  },
  sendText: function () {
    sendText(this);
  },
  getMoreMessages: function (event) {
    getMoreMessages(this);
  },
  sendImage: function () {
    sendImage(this);
  },
  sendMusic: function () {
    sendMusic(this);
  },
  showVoice: function(){
    showVoice(this);
  },
  showKeyboard: function(){
    showKeyboard(this);
  },
  startRecording: function(){
    startRecording(this);
  },
  stopRecording: function(){
    stopRecording(this);
  },
  showEmojis: function(){
    showEmojis(this);
  },
  showMore: function(){
    showMore(this);
  },
  // 以下是事件
  onLoad: function (query) {
    var that = this;
    wx.connectSocket({
      url: 'wss://myim.my56.com'
    })

    wx.onSocketOpen(function (res) {
      console.log("websocket连接成功")
      
      sendMessage(that,'aaaaaaaa','online')
    })
    onLoad(this, query);
  },
  onUnload: function () {
    onUnload(this);
    wx.closeSocket({});
    wx.onSocketClose(function (res) {
      console.log("断开连接")
    })
  },
  onInput: function(event){
    this.setData({
      content: event.detail.value
    });
  },
  onFocus: function(event){
    let { height} = event.detail;
    let adapterHeight = 0;
    console.log(height);
  console.log('=====')
    setKeyboardPos(this, height, adapterHeight);
    hideSoftKeyboard(this);
  },
  onPlayVoice: function(event){
    playVoice(this, event);
  },
  onPlayMusic: function (event){
    playMusic(this, event);
  },
  lookquestion: function (event) {
    console.log(event.detail);
    var message = JSON.parse(JSON.stringify(this.data.questionMessage));
    message.name = 'ResolveQuestion';
    var lists = message.resolves;
    var list = lists[event.detail];
    var link = list.LINK;
    var linkMsg = list.LINKMSG;
    var resolves = splitResolveQuestion(list.DESCMSG);
    message.link = link;
    message.linkMsg = linkMsg;
    message.resolves = resolves;
    var messageList = this.data.messageList;
    messageList.push(message);
    this.setData({
      messageList:messageList,
      scrollTop:1000000 * messageList.length
    });
  },
  onMusicStop: function(event){
    stopMusic(this, event);
  },
  onPreviewImage: function(event){
    previewImage(this, event);
  },
  onHide: function(){
    hideKeyboard(this);
    stopPlayMusic(this);
  },
  onShow: function () {
    wx.onSocketClose(function(res) {
      console.log("断开连接")
    })
    var that = this;
    wx.onSocketMessage(function (res) {
      console.log(res);
      var lists = [];
      var messageList = lists.concat(that.data.messageList);
      var data = JSON.parse(res.data);
      if (data.type == 'getChat') {
        console.log("获取聊天记录");
        var lists = data.list;
        console.log(lists);
        
        for (var index in lists) {
          var list = lists[index];
          var message = {
            uId: list.CHATRECORDS_ID,
            name: list.MSGTYPE == 'picture' ? 'ImageMessage' : 'TextMessage',
            direction: list.FROMUSER == 'kefu' ? 'receiver' : 'sender',
            fromUser: list.FROMUSER == 'kefu' ? '客服小爱' : '我',
            toUser: list.TOUSER,
            sender: {
              avatar: list.FROMUSER == 'kefu' ? '../images/kefu.png' : globalData.userInfo.avatarUrl,
            },
            content: {
              content: list.CONTENT,
              imageUri: list.CONTENT
            }
          }
          messageList.push(message);
        }
        that.setData({
          messageList:messageList
        });
      } else {
        var message = {
          uId: data.timestamp,
          name: 'TextMessage',
          direction: data.fromUser == 'kefu' ? 'receiver' : 'sender',
          fromUser: data.fromUser == 'kefu' ? '客服小爱' : '我',
          toUser: data.toUser,
          sender: {
            avatar: data.fromUser == 'kefu' ? '../images/kefu.png' : globalData.userInfo.avatarUrl,
          },
          content: {
            content: data.content
          }
        }
        messageList.push(message);
        that.setData({
          messageList: messageList
        });
      }
      if (that.data.isFirstLoad) {
        getCommonedQuestions(that);
      } else {
        that.setData({
          scrollTop: 1000000 * messages.length
        })
      }
    })
    wx.onSocketError(function (res) {
      console.log("连接失败")
    })
  }, 
})
function getCommonedQuestions(that) {
  wx.showLoading({
    title: '',
  })
  wx.request({
    url: 'https://wx.my56app.com/appim/getQuestions',
    header: {
      'content-type': 'application/json' // 默认值
    },
    success(res) {
      wx.hideLoading();
      console.log(res.data)
      var lists = res.data.data;
      var arr = [];
      for (var index in lists) {
        var list = lists[index];
        arr.push(list.TITLE);
      }

      var message = {
        uId: new Date().getTime(),
        name: 'CommonQuestion',
        direction: 'receiver',
        fromUser: '客服小爱',
        sender: {
          avatar: '../images/kefu.png',
        },
        link: '',
        linkMsg: '',
        resolves: lists,
        questions: arr
      }
      var messageLists = that.data.messageList;
      var messages = messageLists.concat([message]);
      that.setData({
        messageList:messages,
        questionMessage: message,
        scrollTop: 1000000 * messages.length,
        isFirstLoad: false
      })
    }, fail(res) {
      console.log(res.data)
      wx.hideLoading();
    }
  })
}
function splitResolveQuestion(resolve) {
  var resolves = resolve.split('<br>');
  return resolves;
}




